﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebUI.Models;
using System.Web.Security;

namespace WebUI.Controllers
{
    [Authorize(Roles = "Recuper,Engineer,Doctor,Admin")]
    [GZip()]
    public class RecuperController : _SiteBaseController
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Response.Cache.SetExpires(DateTime.MinValue);

            base.OnActionExecuting(filterContext);
        }

        public ActionResult Index()
        {
            return RedirectToAction("MySfdList");
        }
        protected aspnet_Users GetCurrentuser()
        {
            return SiteUser;
        }
        public ActionResult MySfdList()
        {
            var u = GetCurrentuser();
            var uid = u.UserId;
            var m = DB.QizSubjectObjForDoctors.Where(v => v.Recuper.GuoQi == false && v.Recuper.UserID == uid).Select(v => v.QizSubject).Distinct();
            ViewBag.Hospitals = DB.QizSubjectObjForDoctors.Where(v => v.Recuper.GuoQi == false && v.Recuper.UserID == uid && v.QizSubject != null)
                .Select(v => v.QizSubject).Distinct().Select(s => s.Hospital).Distinct();

            //var m= DB.QizSubjects.Where(v=>v.QizSubjectRecupers.Any(t=>t.RecuperID==uid));
            //var m = new List<QizSubject>{ u.Recuper.QizSubject};
            return View(m);

            //return RedirectToAction("QizSessionEdit", new { SubjectID = u.Recuper.QizSubject.ID });
        }

        [HttpGet]
        public ActionResult RecuperEdit(Guid ID)
        {
            //ViewBag.ReQizSubjects = SiteUser.Department.QizSubjects;
            //var qsids = SiteUser.Department.QizSubjects.Select(v => v.ID);
            //ViewBag.ReQizSmsSubjects = DB.QizSmsSubjects.Where(v => qsids.Contains(v.SubjectID));

            //aspnet_Users m = null;
            //if (ID == Guid.Empty)
            //{
            //    m = new aspnet_Users();
            //    //m.Recuper = new Recuper();
            //}
            //else
            //{
            //    m = DB.aspnet_Users.Where(v => v.UserId == ID).FirstOrDefault();
            //}
            return PartialView(SiteUser);
        }
        [HttpPost]
        public ActionResult RecuperEdit(aspnet_Users m, string Pwd)
        {
            if (!ModelState.IsValid)
            {
                throw new ArgumentException("输入内容有误。");
            }
            aspnet_Users tm = null;
            if (!string.IsNullOrEmpty(Pwd))
            {
                var mu = Membership.GetUser(m.UserName);
                mu.ChangePassword(mu.ResetPassword(), Pwd);
            }


            tm = SiteUser; //DB.aspnet_Users.Where(v=>v.UserId==SiteUser.UserId).First();
            tm.UserName = m.UserName;
            tm.LoweredUserName = m.UserName;

            tm.Address = m.Address;
            tm.BeiZhu = m.BeiZhu;
            tm.BingQuID = m.BingQuID;
            tm.BirthDay = m.BirthDay;
            tm.DepartmentID = m.DepartmentID;
            tm.Email = m.Email;
            tm.Gender = m.Gender;
            tm.HomePhone = m.HomePhone;
            tm.HomePhoneB = m.HomePhoneB;
            tm.HospitalID = m.HospitalID;
            tm.HuanZheLaiYuan = m.HuanZheLaiYuan;
            tm.IDCode = m.IDCode;
            tm.IDCodeType = m.IDCodeType;
            tm.IsDoctorDepManager = false;
            tm.MobileAlias = m.MobileAlias;
            tm.MobileAliasB = m.MobileAliasB;
            tm.OtherPhone = m.OtherPhone;
            tm.OtherPhoneB = m.OtherPhoneB;
            tm.SheBaoHao = m.SheBaoHao;
            DB.SaveChanges();

            FormsAuthentication.SetAuthCookie(tm.UserName, false);

            //SiteUser = DB.aspnet_Users.Where(v => v.UserId == tm.UserId).FirstOrDefault();
            //ViewBag.SiteUser = SiteUser;

            return RedirectToAction("RecuperEdit", new { ID = tm.UserId });

        }

        [HttpGet]
        public ActionResult RecuperEnHospEdit(string ID, Guid? UserID)
        {
            Recuper m = null;
            if (string.IsNullOrEmpty(ID))
            {
                var user = DB.aspnet_Users.First(v => v.UserId == UserID);
                //create new by UserID
                m = new Recuper();
                m.UserID = UserID.Value; m.User = user;
                m.Hospital = SiteUser.Hospital; m.HospitalID = SiteUser.HospitalID;
                m.BingQu = SiteUser.BingQu; m.BingQuID = SiteUser.BingQuID;
                m.Department = SiteUser.Department; m.DepartmentID = SiteUser.DepartmentID;

            }
            else
            {
                //edit by ID
                m = DB.Recupers.FirstOrDefault(v => v.RecuperID == ID);
            }
            return PartialView(m);
        }

        public ActionResult MyQizCommList()//(string Search)
        {
            var qn = from v in DB.SmsSents
                     join d in DB.aspnet_Users on v.SenderName equals d.UserName
                     where v.ReceiverName == SiteUser.UserName && v.SmsType == "医生留言"
                     orderby v.SentTime descending
                     select new CommonSearchValues2<DateTime, string, string>()
                     {
                         V1 = d.Hospital.HospName,
                         V2 = d.Department.DepName,
                         V3 = d.UserName,
                         V4 = v.TextMessage,
                         V11 = v.SentTime.Value,
                         V6 = v.ProcStatus,
                         V0 = d.BingQu.Title,
                     };

            var q = DB.SmsSents.Where(v => v.ReceiverName == SiteUser.UserName).Join(DB.Doctors, v => v.SenderName, d => d.UserName
                , (v, d) => new CommonSearchValues()
                {
                    V1 = d.Hospital.HospName,
                    V2 = d.Department.DepName,
                    V3 = d.UserName,
                    V4 = v.TextMessage,
                    V5 = v.SentTime.Value.ToString().ToString(),
                    V6 = v.ProcStatus,
                    V0 = d.BingQu.Title
                });
            return View(qn);
            //return View(DB.SmsSents.Where(v => v.ReceiverName == SiteUser.UserName));

            //IQueryable<QizSession> m = null;
            //m = DB.QizSessions.Where(v => v.QizSubject.QizSubjectRecupers.Any(t => t.RecuperID == SiteUser.UserId) && v.LastCommentedDoctorID.HasValue);
            //if (!string.IsNullOrWhiteSpace(Search))
            //{
            //    DateTime dt = DateTime.Now;
            //    if (DateTime.TryParse(Search, out dt))
            //    {
            //        m = m.Where(v => (v.Timemark > dt.AddDays(-2) && v.Timemark < dt.AddDays(2)) ||
            //            v.DoctorCommentTime > dt.AddDays(-2) && v.DoctorCommentTime < dt.AddDays(2)
            //            );
            //    }
            //    else
            //    {
            //        m = m.Where(v => v.QizSubject.Title.Contains(Search) || v.aspnet_Users.UserName.Contains(Search) || v.SubmitSrc.Contains(Search) || v.DoctorComment.Contains(Search));
            //    }
            //}
            //return View(m);
        }


        [HttpGet]
        public ActionResult QizSessionEdit(string SubjectID, string ID, string RefAttID)
        {
            var TokenID = DateTime.Now.Ticks.ToString();
            ViewBag.TokenID = TokenID;
            Session["Fix_QizSessionEdit_Token_" + TokenID] = "Yes";
            var m = Services.QizSessionEditInner_Get(SubjectID, ID, RefAttID);
            return ViewOrPartial(m);
        }


        [HttpPost]
        public ActionResult QizSessionEdit(QizSession tm, string TokenID, string RecuperID = "")
        {
            if (Session["Fix_QizSessionEdit_Token_" + TokenID] != null)
            {
                Session.Remove("Fix_QizSessionEdit_Token_" + TokenID);
                var m = Services.QizSessionEditInner_Post(tm, RecuperID);
                Session["Fix_QizSessionEdit_TempSid"] = m.Item1.ID;
                if (m.Item2)
                {
                    return RedirectToAction("QizSessionEdit", new { PreviewOnly = true, ID = m.Item1.ID });
                }
                else
                {
                    ViewBag.TokenID = TokenID;
                    Session["Fix_QizSessionEdit_Token_" + TokenID] = "Yes";
                    return View(m.Item1);
                }
            }
            else
            {
                if (null != Session["Fix_QizSessionEdit_TempSid"])
                {
                    return RedirectToAction("QizSessionEdit", new { PreviewOnly = true, ID = (string)Session["Fix_QizSessionEdit_TempSid"] });
                }
                else
                {
                    throw new SiteException("如果网络速度较慢，可能会耗时较长，请耐心等待，勿重复的提交。");
                }
            }
        }


        public ActionResult Img(string id, bool Preview = false)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var idl = id.ToLower();
                var idext = System.IO.Path.GetExtension(idl);
                string[] exts = { ".png", ".jpg", ".gif", ".jpeg" };

                string fn = null;
                //string fnori = Server.MapPath("~/App_Data/FileDB/" + id);
                string fnOri = "/FileDB/" + id;
                fn = fnOri;

                bool isimg = exts.Contains(idext);
                if (!isimg)
                {
                    return File(GetFileData(id), "application/x-download");
                }
                else
                {
                    if (Preview)
                    {
                        fn = fnOri + ".thumb" + idext;
                        byte[] filedata = null;
                        try
                        {
                            filedata = GetFileData(fn);
                            if (null == filedata || filedata.Length == 0) throw new Exception("Not data");
                        }
                        catch
                        {

                            try
                            {
                                filedata = GetFileData(fnOri);
                                if (null == filedata || filedata.Length == 0) throw new Exception("Not data");
                                System.Web.Helpers.WebImage wi = new System.Web.Helpers.WebImage(filedata);
                                if (wi.Width > 300 || wi.Height > 300) wi.Resize(300, 300, true, true);
                                PutFileData(fn, wi.GetBytes());
                            }
                            catch
                            {
                            }

                            //rebuild previewimg


                        }

                    }
                    return File(GetFileData(fn), "image");
                }
            }
            else
            {
                return Content("No image");
            }
        }
        byte[] GetFileData(string fn)
        {
            StorageLib.IStorageProvider sp = StorageLib.StorageFactory.GetDefaultStorageProvider();
            try
            {
                return sp.GetData(fn);
            }
            catch (Exception ex)
            {
                MvcApplication.Log(ex.Message + "@RecuperController.GetFileData(fn=" + fn);
                return new byte[] { };
            }
        }
        void PutFileData(string fn, byte[] data)
        {
            StorageLib.StorageFactory.GetDefaultStorageProvider().PutData(fn, data);
        }
        public ActionResult QizSessionList(ListViewModel<CommonSearchValues, IQueryable<QizSession>> m = null)
        {
            //ViewBag.Recupers = new aspnet_Users[]{SiteUser};
            var subjects = SiteUser.UserAllRecupers.SelectMany(v => v.QizSubjectObjForDoctors).Select(v => v.QizSubject);
            if (subjects != null)
            {
                ViewBag.Subjects = subjects.Where(s => s != null && (s.SubjectType == "常规随访单" || s.SubjectType == null));//  new QizSubject[]{ SiteUser.Recuper.QizSubject};
            }
            return ViewOrPartial(Services.QizSessionListForRecuper(m));
        }


        public ActionResult QizSmsSessionList(ListViewModel<CommonSearchValues, IQueryable<QizSmsSession>> m = null)
        {
            ViewBag.Recupers = new aspnet_Users[] { SiteUser };
            ViewBag.Subjects = SiteUser.UserAllRecupers.SelectMany(v => v.QizSubjectObjForDoctors).Select(v => v.QizSmsSubject);//new QizSmsSubject[] { SiteUser.Recuper.QizSmsSubject };
            return ViewOrPartial(Services.QizSmsSessionListForAdmin(m));
        }

        [HttpGet]
        public ActionResult QizSmsSessionView(string ID)
        {
            var m = DB.QizSmsSessions.Where(v => v.ID == ID).FirstOrDefault();
            return PartialView(m);
        }

        ///////////////////SMS

        public ActionResult SentSms(ListViewModel<CommonSearchValues, IQueryable<SmsSent>> m = null)
        {
            if (null == m || null == m.SearchFrom)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<SmsSent>>()
                {
                    PageSize = Services.DefaultPageSize,
                    SearchFrom = new CommonSearchValues(),
                    SearchTo = new CommonSearchValues()
                };
            }
            var d = DB.SmsSents.Where(v => v.ReceiverCode == SiteUser.MobileAlias);

            //if (User.IsInRole("Admin") || User.IsInRole("Engineer")) { ;}
            //else if (User.IsInRole("Doctor")) { var o = SiteUser.UserId.ToString(); d = d.Where(v => v.ReceiverCode == o); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V1)) { var w = DateTime.Parse(m.SearchFrom.V1); d = d.Where(v => v.SentTime >= w); }
            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)d.Count() / m.PageSize);
            d = d.OrderByDescending(v => v.SentTime);
            m.Data = d;
            return ViewOrPartial(m);
        }

        ////////////////////////个人档案

        public ActionResult RecuperReport1(string QizSmsSubjectID, int MonthIdx = 0)
        {
            var UserID = SiteUser.UserId;
            var recu = DB.Recupers.FirstOrDefault(v => v.UserID == UserID);
            ViewBag.SmsSubjects = recu.QizSubjectObjForDoctors.Select(v => v.QizSmsSubject).Distinct();
            ViewBag.SmsSubjectID = QizSmsSubjectID;
            ViewBag.UserID = UserID;
            if (MonthIdx == 0)
            {
                return ViewOrPartial(Services.RecuperSummaryReport(SiteUser.UserAllRecupers.Select(v => v.RecuperID).ToArray(), MonthIdx, QizSmsSubjectID));
            }
            else
            {
                return ViewOrPartial(Services.RecuperSummaryReportOfMonthIdx(SiteUser.UserAllRecupers.Select(v => v.RecuperID).ToArray(), MonthIdx, QizSmsSubjectID), "RecuperReportMonth");
            }
        }
        public ActionResult QizItemValueAnalysis(string ItemID, string RecuperID)
        {
            ViewBag.ItemID = ItemID;
            ViewBag.RecuperID = RecuperID;

            ViewBag.Items = DB.QizSessionDetails.Where(v =>
                (v.QizSession.UserID == SiteUser.UserId || v.QizSession.RecuperID == RecuperID) &&
                (v.QizSubjectDefine.QizItem.TypeRef.OptionValue == "2" || v.QizSubjectDefine.QizItem.TypeRef.OptionValue == "4"))
                .Select(v => new { ID = v.QizSubjectDefine.QizItemID, Title = v.QizSubjectDefine.QizItem.Title }).Distinct();

            if (!string.IsNullOrEmpty(ItemID)) ViewBag.ItemType = DB.QizItems.First(v => v.QizItemID == ItemID).TypeRef.OptionValue;
            return ViewOrPartial(null);

        }

        public ActionResult QizItemValueAnalysisLine(string ItemID, string RecuperID, bool Img = false)
        {
            ViewBag.ItemID = ItemID;
            ViewBag.RecuperID = RecuperID;
            ViewBag.ItemTitle = DB.QizItems.First(v => v.QizItemID == ItemID).Title;
            var m = DB.QizSessionDetails.Where(v => (v.QizSession.UserID == SiteUser.UserId || v.QizSession.RecuperID == RecuperID) && v.QizSubjectDefine.QizItemID == ItemID && v.UserValue != null && v.UserValue.Trim() != "").AsQueryable().OrderBy(v => v.QizSession.Timemark);
            return PartialView(m);
        }
        public ActionResult QizItemValueAnalysisPie(string ItemID, string RecuperID, bool Img = false)
        {
            ViewBag.ItemID = ItemID;
            ViewBag.RecuperID = RecuperID;
            ViewBag.ItemTitle = DB.QizItems.First(v => v.QizItemID == ItemID).Title;
            var m = DB.QizSessionDetails.Where(v => (v.QizSession.UserID == SiteUser.UserId || v.QizSession.RecuperID == RecuperID) && v.QizSubjectDefine.QizItemID == ItemID)
                .GroupBy(v => v.UserValue);
            return PartialView(m);
        }

        public ActionResult RecuperReport(string qizSubjectID, int pidx = 0)
        {
            var pageIndex = pidx;
            ViewBag.Flag = "Recuper";
            int pageSize = 10;
            //if (string.IsNullOrEmpty(qizSubjectID))
            //{
            //    qizSubjectID = DB.QizSubjectObjForDoctors.FirstOrDefault(v => v.Recuper.User.UserId == SiteUser.UserId).QizSubjectID;
            //}

            //if (string.IsNullOrEmpty(recuperID))
            //{
            //    recuperID = SiteUser
            //}

            ViewBag.Subjects = DB.QizSubjectObjForDoctors.Where(v => v.Recuper.UserID == SiteUser.UserId).Select(s => s.QizSubject).Distinct();

            var recu = SiteUser.UserAllRecupers.FirstOrDefault(); if (recu == null) recu = new Recuper() { RecuperID = "null", User = SiteUser };
            var recuperID = recu.RecuperID;
            ViewBag.Recuper = recu;//.User.UserName;

            var subj = DB.QizSubjects.FirstOrDefault(v => v.ID == qizSubjectID);
            ViewBag.Subject = subj;
            ViewBag.RecuperID = recuperID;

            if (subj == null) return ViewOrPartial(null);

            List<QizSession> allSession = new List<QizSession>();

            var sessions = DB.QizSessions.Where(v => v.UserID == SiteUser.UserId);
            var smsSessions = DB.QizSmsSessions.Where(v => v.UserID == SiteUser.UserId && v.SessionStatus == 3);

            if (!string.IsNullOrEmpty(qizSubjectID))
            {
                sessions = sessions.Where(v => v.QizSubjectID == qizSubjectID);
                smsSessions = smsSessions.Where(v => v.QizSmsSubjectMonthIdx.QizSmsSubject.SubjectID == qizSubjectID);
            }

            foreach (var session in sessions)
            {
                allSession.Add(session);
            }
            foreach (var session in smsSessions)
            {
                QizSession smsSession = new QizSession();
                smsSession.ID = session.ID;

                smsSession.Timemark = session.Timemark;
                smsSession.Recuper = session.Recuper;
                smsSession.QizSubject = session.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject;
                smsSession.QizSubjectID = session.QizSmsSubjectMonthIdx.QizSmsSubject.QizSubject.ID;
                smsSession.SubmitSrc = "短信";
                //smsSession.QizSessionDetails = new System.Data.Objects.DataClasses.EntityCollection<QizSessionDetail>();
                foreach (var detail in session.QizSmsSessionDetails)
                {
                    QizSessionDetail qizDetail = new QizSessionDetail();
                    qizDetail.UserValue = detail.UserValue;
                    qizDetail.UserSelValue = "-1";
                    qizDetail.QizSessionID = smsSession.ID;
                    qizDetail.QizSubjectDefine = detail.QizSmsSubjDefine.QizSubjectDefine;
                    smsSession.QizSessionDetails.Add(qizDetail);
                }
                allSession.Add(smsSession);
            }
            allSession = allSession.OrderBy(s => s.Timemark).ToList();
            ViewBag.StartTime = allSession.First().Timemark.ToString("yyyy-MM-dd HH:mm");
            ViewBag.PageCount = (int)Math.Ceiling((double)allSession.Count() / pageSize);
            if (pageIndex < 0) pageIndex = 0;
            ViewBag.PageIdx = pageIndex;
            ///pageIndex = pageIndex > 0 ? pageIndex - 1 : 0;
            return ViewOrPartial(allSession.Skip(pageIndex * pageSize).Take(pageSize).ToList());

        }

        public ActionResult UserMemoList(ListViewModel<CommonSearchValues, IQueryable<UserMemo>> m)
        {
            if (null == m || null == m.SearchFrom)
            {
                m = new ListViewModel<CommonSearchValues, IQueryable<UserMemo>>()
                {
                    PageSize = Services.DefaultPageSize,
                    SearchFrom = new CommonSearchValues(),
                    SearchTo = new CommonSearchValues()
                };
            }
            var d = DB.UserMemoes.Where(v => v.UserID == SiteUser.UserId);

            if (!string.IsNullOrEmpty(m.SearchFrom.V1)) { var w = m.SearchFrom.V1.Trim(); d = d.Where(v => v.Title.Contains(w) || v.MemoText.Contains(w)||(v.Recuper!=null&&(v.Recuper.Hospital.HospName.Contains(w)||v.Recuper.Hospital.HospCode.Contains(w)))); }
            if (!string.IsNullOrEmpty(m.SearchFrom.V2)) { var w = DateTime.Parse(m.SearchFrom.V2); d = d.Where(v => v.CreateTime >= w); }
            if (!string.IsNullOrEmpty(m.SearchTo.V2)) { var w = DateTime.Parse(m.SearchTo.V2).AddDays(1); d = d.Where(v => v.CreateTime <= w); }

            m.ItemCount = d.Count();
            m.PageCount = (int)Math.Ceiling((double)d.Count() / m.PageSize);
            d = d.OrderByDescending(v => v.CreateTime);

            m.Data = d.Skip(m.PageSize * m.PageIdx).Take(m.PageSize); ;

            return ViewOrPartial(m);
        }
        [HttpGet]
        public ActionResult UserMemoEdit(string id)
        {
            return PartialView(string.IsNullOrEmpty(id) ? new UserMemo() : DB.UserMemoes.FirstOrDefault(v => v.UserID == SiteUser.UserId && v.ID == id));
        }
        [HttpPost]
        public ActionResult UserMemoEdit(UserMemo m, IEnumerable<HttpPostedFileBase> memopicfile)
        {
            var sir = Services.SaveRequestImage("memopicfile", m.MemoPic);
            var haserror = sir.Item1;
            m.MemoPic = sir.Item2;

            if (m.Timemark <SiteDb.ZeroTime) m.Timemark = SiteDb.ZeroTime;
            m.CreateTime = DateTime.Now;

            if (string.IsNullOrEmpty(m.ID))
            {
                m.UserID = SiteUser.UserId;
                m.ID = DB.NewID();
                m.Timemark = m.CreateTime = DateTime.Now;
                DB.UserMemoes.AddObject(m);
            }
            else
            {
                if (m.UserID != SiteUser.UserId) throw new SiteException("行为错误！");
                var om = DB.UserMemoes.FirstOrDefault(v => v.ID == m.ID && v.UserID == SiteUser.UserId);
                if (null == om) throw new SiteException("数据错误！");

                DB.UserMemoes.ApplyCurrentValues(m);
            }

            if (haserror)
            {
                ModelState.AddModelError("memopic", "图片有问题。");
            }
            else
            {
                DB.SaveChanges();
            }

            return RedirectToAction("UserMemoList", new { IsView = true });

            //return PartialView(m);
        }
    }
}
